<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Spring Security 入门 | Unknown Blog</title><meta name="author" content="Ris Pika"><meta name="copyright" content="Ris Pika"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="官方文档: https:&#x2F;&#x2F;www.springcloud.cc&#x2F;spring-security.html">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Security 入门">
<meta property="og:url" content="https://unkonwn.online/2023/02/26/spring-security/index.html">
<meta property="og:site_name" content="Unknown Blog">
<meta property="og:description" content="官方文档: https:&#x2F;&#x2F;www.springcloud.cc&#x2F;spring-security.html">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://pic.unkonwn.online/wallhaven-d681jm.jpg?imageView/1/w/500/h/500">
<meta property="article:published_time" content="2023-02-26T11:23:51.000Z">
<meta property="article:modified_time" content="2023-03-01T10:54:16.970Z">
<meta property="article:author" content="Ris Pika">
<meta property="article:tag" content="SpringSecurity">
<meta property="article:tag" content="入门">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://pic.unkonwn.online/wallhaven-d681jm.jpg?imageView/1/w/500/h/500"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://unkonwn.online/2023/02/26/spring-security/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"Traditional Chinese Activated Manually","cht_to_chs":"Simplified Chinese Activated Manually","day_to_night":"Dark Mode Activated Manually","night_to_day":"Light Mode Activated Manually","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring Security 入门',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-01 18:54:16'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">Loading...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="http://pic.unkonwn.online//20140802211120_t34dW.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">13</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/upadte/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/myself/"><i class="fa-fw fa fa-id-card"></i><span> Myself</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 1</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://pic.unkonwn.online/wallhaven-d681jm.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Unknown Blog"><span class="site-name">Unknown Blog</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/upadte/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/myself/"><i class="fa-fw fa fa-id-card"></i><span> Myself</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 1</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring Security 入门</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-02-26T11:23:51.000Z" title="Created 2023-02-26 19:23:51">2023-02-26</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-03-01T10:54:16.970Z" title="Updated 2023-03-01 18:54:16">2023-03-01</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Spring Security 入门"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="官方文档-https-www-springcloud-cc-spring-security-html"><a href="#官方文档-https-www-springcloud-cc-spring-security-html" class="headerlink" title="官方文档: https://www.springcloud.cc/spring-security.html"></a>官方文档: <a target="_blank" rel="noopener" href="https://www.springcloud.cc/spring-security.html">https://www.springcloud.cc/spring-security.html</a></h2><span id="more"></span>

<h2 id="1-config-自定登录校验信息"><a href="#1-config-自定登录校验信息" class="headerlink" title="1. config 自定登录校验信息"></a>1. config 自定登录校验信息</h2><h3 id="0-yaml-修改-最简单"><a href="#0-yaml-修改-最简单" class="headerlink" title="0. yaml 修改 (最简单)"></a>0. <code>yaml </code>修改 (最简单)</h3><pre><code><figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">security:</span></span><br><span class="line">    <span class="attr">user:</span></span><br><span class="line">      <span class="attr">password:</span> <span class="number">123</span></span><br><span class="line">      <span class="attr">name:</span> <span class="string">ris</span></span><br></pre></td></tr></table></figure>
</code></pre>
<h3 id="1-继承WebSecurityConfigurerAdapter-重写configure方法"><a href="#1-继承WebSecurityConfigurerAdapter-重写configure方法" class="headerlink" title="1. 继承WebSecurityConfigurerAdapter 重写configure方法"></a>1. 继承<code>WebSecurityConfigurerAdapter </code>重写<code>configure</code>方法</h3><pre><code><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserDetailsService userDetailsService;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123; <span class="comment">//重写configure</span></span><br><span class="line">        auth.userDetailsService(userDetailsService).passwordEncoder(password());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    PasswordEncoder <span class="title function_">password</span><span class="params">()</span>&#123;<span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</code></pre>
<h3 id="2-实现-userDetailsService-接口并通过-sql-语句查询"><a href="#2-实现-userDetailsService-接口并通过-sql-语句查询" class="headerlink" title="2. 实现 userDetailsService 接口并通过 sql 语句查询"></a>2. 实现 <code>userDetailsService </code>接口并通过 <code>sql </code>语句查询</h3><pre><code><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Service(&quot;userDetailsService&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserDetailsServiceImpl</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        <span class="comment">// 查找用户</span></span><br><span class="line">        QueryWrapper&lt;com.example.springsecurity.domain.User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line">        wrapper.eq(<span class="string">&quot;name&quot;</span>,username);</span><br><span class="line">        com.example.springsecurity.domain.<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userMapper.selectOne(wrapper);</span><br><span class="line">        <span class="keyword">if</span> (user == <span class="literal">null</span>) &#123; <span class="comment">//数据库没有该成员</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UsernameNotFoundException</span>(<span class="string">&quot;用户名不存在!&quot;</span>); <span class="comment">//抛出异常</span></span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(user);</span><br></pre></td></tr></table></figure>

        List&lt;GrantedAuthority&gt; auth = AuthorityUtils.commaSeparatedStringToAuthorityList(&quot;ris&quot;); //权限控制~!
        return new User(user.getName(),new BCryptPasswordEncoder().encode(user.getPassword()),auth);
    &#125;
&#125;
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">*   其中  `BCryptPasswordEncoder` 可以对密码进行加密处理!</span><br><span class="line"></span><br><span class="line">## 2. 自定义登录页面</span><br><span class="line"></span><br><span class="line">*   重写`configure`方法实现</span><br><span class="line"></span><br><span class="line">    ```java</span><br><span class="line">        @Override</span><br><span class="line">        protected void configure(HttpSecurity http) throws Exception &#123;</span><br><span class="line">            http.formLogin() //自定义登录界面</span><br><span class="line">                    .loginPage(&quot;/login.html&quot;) //自定义登录html</span><br><span class="line">                    .loginProcessingUrl(&quot;/user/login&quot;) //自定义登录访问路径</span><br><span class="line">                    .defaultSuccessUrl(&quot;/test/index&quot;).permitAll() //自定义登录之后-&gt;跳转页面</span><br><span class="line">                    .and().authorizeRequests()</span><br><span class="line">                    .antMatchers(&quot;/&quot;,&quot;/test/hello&quot;,&quot;user/login&quot;).permitAll() //配置不拦截路径</span><br><span class="line">                    .anyRequest().authenticated() //所有请求都要访问</span><br><span class="line">                    .and().csrf().disable(); //关闭csrf防护</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
</code></pre>
<ul>
<li><p>注意 登录页面 <code>name</code>必须采用 <code>username</code>和<code>password</code></p>
<pre><code><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/user/login&quot;</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span>&gt;</span></span><br><span class="line">    用户名:<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    密码:<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span> <span class="attr">type</span>=<span class="string">&quot;password&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;login&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
<h2 id="3-权限控制"><a href="#3-权限控制" class="headerlink" title="3.权限控制"></a>3.权限控制</h2><ol>
<li><p>使用<code>hasAuthority</code>方法进行权限控制</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        http.formLogin() <span class="comment">//自定义登录界面</span></span><br><span class="line">                .loginPage(<span class="string">&quot;/login.html&quot;</span>) <span class="comment">//自定义登录html</span></span><br><span class="line">                .loginProcessingUrl(<span class="string">&quot;/user/login&quot;</span>) <span class="comment">//自定义登录访问路径</span></span><br><span class="line">                .defaultSuccessUrl(<span class="string">&quot;/test/index&quot;</span>).permitAll() <span class="comment">//自定义登录之后-&gt;跳转页面</span></span><br><span class="line">                .and().authorizeRequests()</span><br><span class="line">                .antMatchers(<span class="string">&quot;/&quot;</span>,<span class="string">&quot;/test/hello&quot;</span>,<span class="string">&quot;user/login&quot;</span>).permitAll() <span class="comment">//配置不拦截路径</span></span><br><span class="line">                <span class="comment">// 只有admin用户才有权限对下面地址进行访问!</span></span><br><span class="line">                .antMatchers(<span class="string">&quot;/test/index&quot;</span>).hasAuthority(<span class="string">&quot;admin&quot;</span>)</span><br><span class="line">                .anyRequest().authenticated() <span class="comment">//所有请求都要访问</span></span><br><span class="line">                .and().csrf().disable(); <span class="comment">//关闭csrf防护</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>  测试会发现<code>(type=Forbidden, status=403).</code> ==403没有权限访问==</li>
</ul>
</li>
<li><p> 使用<code>hasAnyAuthority</code>方法进行权限控制</p>
</li>
</ol>
<ul>
<li><p>可以配置多个权限者</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        http.formLogin() <span class="comment">//自定义登录界面</span></span><br><span class="line">                .loginPage(<span class="string">&quot;/login.html&quot;</span>) <span class="comment">//自定义登录html</span></span><br><span class="line">                .loginProcessingUrl(<span class="string">&quot;/user/login&quot;</span>) <span class="comment">//自定义登录访问路径</span></span><br><span class="line">                .defaultSuccessUrl(<span class="string">&quot;/test/index&quot;</span>).permitAll() <span class="comment">//自定义登录之后-&gt;跳转页面</span></span><br><span class="line">                .and().authorizeRequests()</span><br><span class="line">                .antMatchers(<span class="string">&quot;/&quot;</span>,<span class="string">&quot;/test/hello&quot;</span>,<span class="string">&quot;user/login&quot;</span>).permitAll() <span class="comment">//配置不拦截路径</span></span><br><span class="line">                .antMatchers(<span class="string">&quot;/test/index&quot;</span>).hasAnyAuthority(<span class="string">&quot;admin&quot;</span>,<span class="string">&quot;ris&quot;</span>) <span class="comment">//配置多用户</span></span><br><span class="line">                .anyRequest().authenticated() <span class="comment">//所有请求都要访问</span></span><br><span class="line">                .and().csrf().disable(); <span class="comment">//关闭csrf防护</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<ol>
<li> 使用<code>hasRole</code>方法</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        http.formLogin() <span class="comment">//自定义登录界面</span></span><br><span class="line">                .loginPage(<span class="string">&quot;/login.html&quot;</span>) <span class="comment">//自定义登录html</span></span><br><span class="line">                .loginProcessingUrl(<span class="string">&quot;/user/login&quot;</span>) <span class="comment">//自定义登录访问路径</span></span><br><span class="line">                .defaultSuccessUrl(<span class="string">&quot;/test/index&quot;</span>).permitAll() <span class="comment">//自定义登录之后-&gt;跳转页面</span></span><br><span class="line">                .and().authorizeRequests()</span><br><span class="line">                .antMatchers(<span class="string">&quot;/&quot;</span>,<span class="string">&quot;/test/hello&quot;</span>,<span class="string">&quot;user/login&quot;</span>).permitAll() <span class="comment">//配置不拦截路径</span></span><br><span class="line">                .antMatchers(<span class="string">&quot;/test/index&quot;</span>).hasRole(<span class="string">&quot;ris&quot;</span>) <span class="comment">//配置ROLE用户</span></span><br><span class="line">                .anyRequest().authenticated() <span class="comment">//所有请求都要访问</span></span><br><span class="line">                .and().csrf().disable(); <span class="comment">//关闭csrf防护</span></span><br><span class="line">    &#125;</span><br><span class="line">```</span><br><span class="line"></span><br><span class="line">*   需要注意的是!Role本质就是给用户规范化 ris -&gt; ROLE\_ris</span><br><span class="line">*   所以权限者需要如下设置 重写`loadUserByUsername`</span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        <span class="comment">// 查找用户</span></span><br><span class="line">        QueryWrapper&lt;com.example.springsecurity.domain.User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line">        wrapper.eq(<span class="string">&quot;name&quot;</span>,username);</span><br><span class="line">        com.example.springsecurity.domain.<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userMapper.selectOne(wrapper);</span><br><span class="line">        <span class="comment">//判断</span></span><br><span class="line">        <span class="keyword">if</span> (user == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UsernameNotFoundException</span>(<span class="string">&quot;用户名不存在!&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 以逗号隔开 , role 以 ROLE_ 拼接</span></span><br><span class="line">        List&lt;GrantedAuthority&gt; auth = AuthorityUtils.commaSeparatedStringToAuthorityList(<span class="string">&quot;ris,ROLE_ris&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">User</span>(user.getName(),<span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>().encode(user.getPassword()),auth);</span><br><span class="line">    &#125;</span><br><span class="line">```</span><br></pre></td></tr></table></figure>

<ol>
<li> <code>HasAnyRole</code>如上可以多用户权限访问</li>
</ol>
<h2 id="4-自定义403页面"><a href="#4-自定义403页面" class="headerlink" title="4. 自定义403页面"></a>4. 自定义403页面</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">       <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">           <span class="comment">//自定义403无权限访问页面!</span></span><br><span class="line">           http.exceptionHandling().accessDeniedPage(<span class="string">&quot;/403.html&quot;</span>);</span><br><span class="line">           http.formLogin() <span class="comment">//自定义登录界面</span></span><br><span class="line">                   .loginPage(<span class="string">&quot;/login.html&quot;</span>) <span class="comment">//自定义登录html</span></span><br><span class="line">                   .loginProcessingUrl(<span class="string">&quot;/user/login&quot;</span>) <span class="comment">//自定义登录访问路径</span></span><br><span class="line">                   .defaultSuccessUrl(<span class="string">&quot;/test/index&quot;</span>).permitAll() <span class="comment">//自定义登录之后-&gt;跳转页面</span></span><br><span class="line">                   .and().authorizeRequests()</span><br><span class="line">                   .antMatchers(<span class="string">&quot;/&quot;</span>,<span class="string">&quot;/test/hello&quot;</span>,<span class="string">&quot;user/login&quot;</span>).permitAll() <span class="comment">//配置不拦截路径</span></span><br><span class="line">                   .antMatchers(<span class="string">&quot;/test/index&quot;</span>).hasRole(<span class="string">&quot;ris&quot;</span>) <span class="comment">//配置ROLE用户</span></span><br><span class="line">                   .anyRequest().authenticated() <span class="comment">//所有请求都要访问</span></span><br><span class="line">                   .and().csrf().disable(); <span class="comment">//关闭csrf防护</span></span><br><span class="line">       &#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-Security注解开发"><a href="#5-Security注解开发" class="headerlink" title="5. Security注解开发"></a>5. Security注解开发</h2><h3 id="1-Secured-多角色用逗号分隔"><a href="#1-Secured-多角色用逗号分隔" class="headerlink" title="1. @Secured 多角色用逗号分隔"></a><code>1. @Secured</code> 多角色用逗号分隔</h3><pre><code>1. 在主函数开启注解开发!(否则无法使用注解开发)

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true) //开启注解开发!
public class SpringSecurityApplication &#123;

    public static void main(String[] args) &#123;
        SpringApplication.run(SpringSecurityApplication.class, args);
    &#125;

&#125;
</code></pre>
<ol>
<li><p>在Controller层中使用注解!</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Secured(&quot;ROLE_ris&quot;)</span> <span class="comment">//只有ROLE_ris可以执行</span></span><br><span class="line">   <span class="meta">@GetMapping(&quot;/ris&quot;)</span></span><br><span class="line">   <span class="keyword">public</span> String <span class="title function_">adminCanDo</span><span class="params">()</span> &#123;</span><br><span class="line">       <span class="keyword">return</span> <span class="string">&quot;you are ris!!!&quot;</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">### <span class="number">2.</span> `<span class="meta">@PreAuthoreize</span>`注解</span><br><span class="line"></span><br><span class="line">+ 方法执行之__前__进行校验</span><br><span class="line"></span><br><span class="line">*   同样需要开启</span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)</span> <span class="comment">//开启注解开发!</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SpringSecurityApplication</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(SpringSecurityApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>
<ul>
<li>使用注解开发</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@PreAuthorize(&quot;hasAnyAuthority(&#x27;ris&#x27;)&quot;)</span></span><br><span class="line"><span class="meta">@GetMapping(&quot;/ris&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">adminCanDo</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;you are ris!!!&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-PostAuthorize-注解"><a href="#3-PostAuthorize-注解" class="headerlink" title="3. @PostAuthorize 注解"></a>3. <code>@PostAuthorize</code> 注解</h3><ul>
<li>  方法执行之__后__进行校验</li>
<li>  同样需要开启!<code>prePostEnabled = true</code></li>
<li>  然后再Controller上执行,与上面并无异同!不再展示代码!</li>
</ul>
<h3 id="4-PreFilter-注解"><a href="#4-PreFilter-注解" class="headerlink" title="4. @PreFilter 注解"></a>4. <code>@PreFilter</code> 注解</h3><ul>
<li>  方法返回数据进行过滤</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/getAll&quot;)</span></span><br><span class="line"><span class="meta">@PostAuthorize(&quot;hasAnyAuthority(&#x27;ris&#x27;)&quot;)</span></span><br><span class="line"><span class="meta">@PostFilter(&quot;filterObject.name == &#x27;ris&#x27;&quot;)</span></span><br><span class="line"><span class="keyword">public</span> List&lt;User&gt; <span class="title function_">getAll</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="comment">// 模拟数据</span></span><br><span class="line">    ArrayList&lt;User&gt; users = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">    users.add(<span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">1</span>, <span class="string">&quot;ris&quot;</span>, <span class="string">&quot;1233&quot;</span>));</span><br><span class="line">    users.add(<span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">2</span>, <span class="string">&quot;admin&quot;</span>, <span class="string">&quot;1233&quot;</span>));</span><br><span class="line">    users.add(<span class="keyword">new</span> <span class="title class_">User</span>(<span class="number">3</span>, <span class="string">&quot;asdasd&quot;</span>, <span class="string">&quot;1233&quot;</span>));</span><br><span class="line">    <span class="keyword">return</span> users;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>返回数据</p>
  <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">[</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">        <span class="attr">&quot;id&quot;</span><span class="punctuation">:</span> <span class="number">1</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;name&quot;</span><span class="punctuation">:</span> <span class="string">&quot;ris&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;password&quot;</span><span class="punctuation">:</span> <span class="string">&quot;1233&quot;</span></span><br><span class="line">    <span class="punctuation">&#125;</span></span><br><span class="line"><span class="punctuation">]</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="5-PostFilter-注解"><a href="#5-PostFilter-注解" class="headerlink" title="5. @PostFilter 注解"></a>5. <code>@PostFilter</code> 注解</h3><ul>
<li><p>  传入方法数据进行过滤</p>
</li>
<li><p>  同上,只不过是对__传入方法__做处理!</p>
</li>
</ul>
<h2 id="6-自定义用户注销功能"><a href="#6-自定义用户注销功能" class="headerlink" title="6. 自定义用户注销功能"></a>6. 自定义用户注销功能</h2><ol>
<li><p>配置类修改 <code>configure</code>类</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//自定义注销</span></span><br><span class="line">        http.logout().logoutUrl(<span class="string">&quot;/logout&quot;</span>)</span><br><span class="line">                .logoutSuccessUrl(<span class="string">&quot;/login.html&quot;</span>).permitAll();</span><br></pre></td></tr></table></figure></li>
</ol>
<h2 id="7-自定登录实现"><a href="#7-自定登录实现" class="headerlink" title="7. 自定登录实现"></a>7. 自定登录实现</h2><h3 id="1-原理"><a href="#1-原理" class="headerlink" title="1. 原理"></a>1. 原理</h3><ol>
<li> 使用cookie技术实现</li>
<li> 原理图</li>
</ol>
<p><img src= "" data-lazy-src="C:\Users\RIS\AppData\Roaming\Typora\typora-user-images\image-20230121154326684.png" alt="image-20230121154326684"></p>
<p><img src= "" data-lazy-src="C:\Users\RIS\AppData\Roaming\Typora\typora-user-images\image-20230121154502856.png" alt="image-20230121154502856"></p>
<h3 id="2-实现"><a href="#2-实现" class="headerlink" title="2. 实现"></a>2. 实现</h3><h4 id="1-数据库创建"><a href="#1-数据库创建" class="headerlink" title="1. 数据库创建"></a>1. 数据库创建</h4><ul>
<li>  用于保存token的数据,以便对照前端cookie</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">create table `persistent_logins` (</span><br><span class="line">	`username` VARCHAR(64) NOT NULL,</span><br><span class="line">	`series` VARCHAR(64) NOT NULL,</span><br><span class="line">	`token` VARCHAR(64) NOT NULL,</span><br><span class="line">	`last_used` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,</span><br><span class="line">	PRIMARY KEY (`series`)</span><br><span class="line">) ENGINE=INNODB DEFAULT CHARSET=utf8;</span><br></pre></td></tr></table></figure>

<h4 id="2-配置类修改"><a href="#2-配置类修改" class="headerlink" title="2. 配置类修改"></a>2. 配置类修改</h4><ul>
<li>  注入数据库</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> DataSource dataSource;</span><br></pre></td></tr></table></figure>

<ul>
<li>  自定义Bean</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> PersistentTokenRepository <span class="title function_">persistentTokenRepository</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">JdbcTokenRepositoryImpl</span> <span class="variable">jdbcTokenRepository</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">JdbcTokenRepositoryImpl</span>();</span><br><span class="line">    jdbcTokenRepository.setDataSource(dataSource);</span><br><span class="line">    <span class="comment">//jdbcTokenRepository.setCreateTableOnStartup(true); //自动可以创建数据库!</span></span><br><span class="line">    <span class="keyword">return</span> jdbcTokenRepository;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-configure修改"><a href="#3-configure修改" class="headerlink" title="3. configure修改"></a>3. <code>configure</code>修改</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">.and().rememberMe().tokenRepository(persistentTokenRepository()) <span class="comment">//记住我!</span></span><br><span class="line">                .tokenValiditySeconds(<span class="number">60</span>) <span class="comment">//设置有效时长默认秒单位</span></span><br></pre></td></tr></table></figure>

<h4 id="4-html修改"><a href="#4-html修改" class="headerlink" title="4. html修改"></a>4. html修改</h4><ul>
<li>  复选框 <code>name</code> 必须为 <code>remember-me</code></li>
<li>  才能被spring security框架所识别!!</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/user/login&quot;</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span>&gt;</span></span><br><span class="line">    用户名:<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    密码:<span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span> <span class="attr">type</span>=<span class="string">&quot;password&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;checkbox&quot;</span> <span class="attr">name</span>=<span class="string">&quot;remember-me&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;login&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="8-Spring-Security-CSRF-跨站请求伪造"><a href="#8-Spring-Security-CSRF-跨站请求伪造" class="headerlink" title="8. Spring Security CSRF (跨站请求伪造)"></a>8. Spring Security CSRF (跨站请求伪造)</h2><ul>
<li><p>  Spring Security 4.0开始 默认开启CSRF</p>
</li>
<li><p>  会对PATCH, POST, PUT 和 DELETE方法进行保护!!!</p>
</li>
<li><p>可以进行关闭!</p>
  <figure class="highlight java"><table><tr><td class="code"><pre><span class="line">http.csrf().disable();</span><br></pre></td></tr></table></figure></li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://unkonwn.online">Ris Pika</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://unkonwn.online/2023/02/26/spring-security/">https://unkonwn.online/2023/02/26/spring-security/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/SpringSecurity/">SpringSecurity</a><a class="post-meta__tags" href="/tags/%E5%85%A5%E9%97%A8/">入门</a><a class="post-meta__tags" href="/tags/spring/">spring</a></div><div class="post_share"><div class="social-share" data-image="http://pic.unkonwn.online/wallhaven-d681jm.jpg?imageView/1/w/500/h/500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://lib.baomitu.com/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://lib.baomitu.com/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-full"><a href="/2023/02/26/jwt/" title="五分钟JWT入门"><img class="cover" src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">五分钟JWT入门</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2023/02/26/jwt/" title="五分钟JWT入门"><img class="cover" src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-26</div><div class="title">五分钟JWT入门</div></div></a></div><div><a href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-gpw787.jpg?imageView/1/w/500/h/500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-01</div><div class="title">JAVA 从0到helloworld</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="http://pic.unkonwn.online//20140802211120_t34dW.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ris Pika</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">13</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/rispika/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3-https-www-springcloud-cc-spring-security-html"><span class="toc-number">1.</span> <span class="toc-text">官方文档: https:&#x2F;&#x2F;www.springcloud.cc&#x2F;spring-security.html</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-config-%E8%87%AA%E5%AE%9A%E7%99%BB%E5%BD%95%E6%A0%A1%E9%AA%8C%E4%BF%A1%E6%81%AF"><span class="toc-number">2.</span> <span class="toc-text">1. config 自定登录校验信息</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#0-yaml-%E4%BF%AE%E6%94%B9-%E6%9C%80%E7%AE%80%E5%8D%95"><span class="toc-number">2.1.</span> <span class="toc-text">0. yaml 修改 (最简单)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E7%BB%A7%E6%89%BFWebSecurityConfigurerAdapter-%E9%87%8D%E5%86%99configure%E6%96%B9%E6%B3%95"><span class="toc-number">2.2.</span> <span class="toc-text">1. 继承WebSecurityConfigurerAdapter 重写configure方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%AE%9E%E7%8E%B0-userDetailsService-%E6%8E%A5%E5%8F%A3%E5%B9%B6%E9%80%9A%E8%BF%87-sql-%E8%AF%AD%E5%8F%A5%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.3.</span> <span class="toc-text">2. 实现 userDetailsService 接口并通过 sql 语句查询</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E6%9D%83%E9%99%90%E6%8E%A7%E5%88%B6"><span class="toc-number">3.</span> <span class="toc-text">3.权限控制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E8%87%AA%E5%AE%9A%E4%B9%89403%E9%A1%B5%E9%9D%A2"><span class="toc-number">4.</span> <span class="toc-text">4. 自定义403页面</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-Security%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%8F%91"><span class="toc-number">5.</span> <span class="toc-text">5. Security注解开发</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-Secured-%E5%A4%9A%E8%A7%92%E8%89%B2%E7%94%A8%E9%80%97%E5%8F%B7%E5%88%86%E9%9A%94"><span class="toc-number">5.1.</span> <span class="toc-text">1. @Secured 多角色用逗号分隔</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-PostAuthorize-%E6%B3%A8%E8%A7%A3"><span class="toc-number">5.2.</span> <span class="toc-text">3. @PostAuthorize 注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-PreFilter-%E6%B3%A8%E8%A7%A3"><span class="toc-number">5.3.</span> <span class="toc-text">4. @PreFilter 注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-PostFilter-%E6%B3%A8%E8%A7%A3"><span class="toc-number">5.4.</span> <span class="toc-text">5. @PostFilter 注解</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%94%A8%E6%88%B7%E6%B3%A8%E9%94%80%E5%8A%9F%E8%83%BD"><span class="toc-number">6.</span> <span class="toc-text">6. 自定义用户注销功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-%E8%87%AA%E5%AE%9A%E7%99%BB%E5%BD%95%E5%AE%9E%E7%8E%B0"><span class="toc-number">7.</span> <span class="toc-text">7. 自定登录实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%8E%9F%E7%90%86"><span class="toc-number">7.1.</span> <span class="toc-text">1. 原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%AE%9E%E7%8E%B0"><span class="toc-number">7.2.</span> <span class="toc-text">2. 实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E6%95%B0%E6%8D%AE%E5%BA%93%E5%88%9B%E5%BB%BA"><span class="toc-number">7.2.1.</span> <span class="toc-text">1. 数据库创建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E9%85%8D%E7%BD%AE%E7%B1%BB%E4%BF%AE%E6%94%B9"><span class="toc-number">7.2.2.</span> <span class="toc-text">2. 配置类修改</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-configure%E4%BF%AE%E6%94%B9"><span class="toc-number">7.2.3.</span> <span class="toc-text">3. configure修改</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-html%E4%BF%AE%E6%94%B9"><span class="toc-number">7.2.4.</span> <span class="toc-text">4. html修改</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-Spring-Security-CSRF-%E8%B7%A8%E7%AB%99%E8%AF%B7%E6%B1%82%E4%BC%AA%E9%80%A0"><span class="toc-number">8.</span> <span class="toc-text">8. Spring Security CSRF (跨站请求伪造)</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-gpw787.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JAVA 从0到helloworld"/></a><div class="content"><a class="title" href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld">JAVA 从0到helloworld</a><time datetime="2023-03-01T14:32:08.000Z" title="Created 2023-03-01 22:32:08">2023-03-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JUC学习日记1"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-6dl2yw.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC学习日记1"/></a><div class="content"><a class="title" href="/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JUC学习日记1">JUC学习日记1</a><time datetime="2023-03-01T12:52:40.000Z" title="Created 2023-03-01 20:52:40">2023-03-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-x6ewo3.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JAVA线程池学习日记1"/></a><div class="content"><a class="title" href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1">JAVA线程池学习日记1</a><time datetime="2023-02-28T10:02:52.000Z" title="Created 2023-02-28 18:02:52">2023-02-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/27/blocking-queue/" title="初学BlockingQueue"><img src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-we52yp.jpg?imageView/1/w/240/h/240" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="初学BlockingQueue"/></a><div class="content"><a class="title" href="/2023/02/27/blocking-queue/" title="初学BlockingQueue">初学BlockingQueue</a><time datetime="2023-02-27T07:50:33.000Z" title="Created 2023-02-27 15:50:33">2023-02-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/26/jwt/" title="五分钟JWT入门"><img src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="五分钟JWT入门"/></a><div class="content"><a class="title" href="/2023/02/26/jwt/" title="五分钟JWT入门">五分钟JWT入门</a><time datetime="2023-02-26T13:39:36.000Z" title="Created 2023-02-26 21:39:36">2023-02-26</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Ris Pika</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">unknown!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.js"></script><div class="js-pjax"></div><script defer src="/live2d-widget/autoload.js"></script><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">Search</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  Loading the Database</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>